package com.lancoo.edu.platform.operation.commons.service.bo.school;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.lancoo.edu.platform.operation.commons.domain.vo.school.Semester;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 学期信息【响应】业务逻辑
 * @author lzh
 */
@Service
@AllArgsConstructor
@Slf4j
public class TermInfoBoService {
    /**
     * 获取学期所有周次
     * @param eduId 教育局ID
     * @param userId 用户ID
     * @param userType 用户类型
     * @return 周次列表
     */
    public Semester getWeekInfoByDate(String eduId, String userId, Integer userType, Date date){
        Semester weekInfo = new Semester();
        final Map<String, String> weekDate = getWeekDate(date);
        Integer weekNo = Integer.valueOf(weekDate.get("weekNo"));
        weekInfo = new Semester(weekDate.get("mondayDate"), "星期一", weekNo,weekDate.get("sundayDate"), "星期天");
        return weekInfo;
    }

    /**
     * 获取当前学年学期信息 (适配局端)
     * @param eduId 教育局ID
     * @return 学年学期信息
     */
    public Semester getSemester(String eduId) {
        Semester semester = new Semester();
        // 获取当月本周次信息
        Date date = new Date();
        int weekNo = DateUtil.weekOfMonth(date);
        semester.setCurrentWeek(weekNo);
        semester.setEduId(eduId);
        // 学期信息，开始结束为
        semester.setTermStartDate(DateUtil.offset(date, DateField.YEAR, -1).toString());
        semester.setTermEndDate(DateUtil.offset(date, DateField.YEAR, 1).toString());
        return semester;
    }

    /**
     * 获取当前时间所在周的周一和周日的日期时间
     * @return 周次对应时间
     */
    public static Map<String,String> getWeekDate(Date date) {
        Map<String,String> map = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        // 设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        // 获得当前日期是一个星期的第几天
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
        if(dayWeek==1){
            dayWeek = 8;
        }
        //根据日历的规则，给当前日期减去星期几与一个星期第一天的差值
        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - dayWeek);
        Date mondayDate = cal.getTime();
        String weekBegin = sdf.format(mondayDate);

        cal.add(Calendar.DATE, 4 +cal.getFirstDayOfWeek());
        Date sundayDate = cal.getTime();
        String weekEnd = sdf.format(sundayDate);

        map.put("mondayDate", weekBegin);
        map.put("sundayDate", weekEnd);

        Integer weekNo = DateUtil.weekOfMonth(date);
        map.put("weekNo", Integer.toString(weekNo));

        return map;
    }


}
